package com.web.note;



import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

 

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;
 

public class HttpTookit {

 

    public static final int POST = 1;

    public static final int GET = 2;

    public static final int HttpClientPost = 3;

 

    /**
     * 保存数据

     *

     * @param title

     *            标题

     * @param length

     *            时长

     * @param flag

     *            true则使用POST请求 false使用GET请求

     * @return 是否保存成功

     * @throws Exception

     */

    public static String save(String path,

            int flag, Map<String, String> params) throws Exception {

//        Map<String, String> params = new HashMap<String, String>();
//
//        params.put("goodsTitle", title);
//
//        params.put("photoURL", timelength);

        switch (flag) {

        case POST:

            return sendPOSTRequest(path, params, "UTF-8");

        case GET:

            return sendGETRequest(path, params, "UTF-8");

        case HttpClientPost:

            return sendHttpClientPOSTRequest(path, params, "UTF-8");

        }

        return "false";

    }

 

    /**
054
     * 通过HttpClient框架发送POST请求
055
     * HttpClient该框架已经集成在android开发包中
056
     * 个人认为此框架封装了很多的工具类，性能比不上自己手写的下面两个方法
057
     * 但是该方法可以提高程序员的开发速度，降低开发难度
058
     * @param path
059
     *            请求路径
060
     * @param params
061
     *            请求参数
062
     * @param encoding
063
     *            编码
064
     * @return 请求是否成功
065
     * @throws Exception
066
     */

    private static String sendHttpClientPOSTRequest(String path,

            Map<String, String> params, String encoding) throws Exception {

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放请求参数

        if (params != null && !params.isEmpty()) {

            for (Map.Entry<String, String> entry : params.entrySet()) 
             //BasicNameValuePair实现了NameValuePair接口
               pairs.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);    //pairs:请求参数   encoding:编码方式

        HttpPost httpPost = new HttpPost(path); //path:请求路径

        httpPost.setEntity(entity);

        DefaultHttpClient client = new DefaultHttpClient(); //相当于浏览器

        HttpResponse response = client.execute(httpPost);  //相当于执行POST请求

        //取得状态行中的状态码

        if (response.getStatusLine().getStatusCode() == 200) {

            return "true";

        }
		return "false";

    }

    /**
091
     * 发送POST请求
092
     *
093
     * @param path
094
     *            请求路径
095
     * @param params
096
     *            请求参数
097
     * @param encoding
098
     *            编码
099
     * @return 请求是否成功
100
     * @throws Exception
101
     */


    private static String sendPOSTRequest(String path,

            Map<String, String> params, String encoding) throws Exception {
  StringBuilder data = new StringBuilder();

        if (params != null && !params.isEmpty()) {

            for (Map.Entry<String, String> entry : params.entrySet()) {

                data.append(entry.getKey()).append("=");

                data.append(URLEncoder.encode(entry.getValue(), encoding));// 编码
         data.append('&');

            }

            data.deleteCharAt(data.length() - 1);
      }

        byte[] entity = data.toString().getBytes(); // 得到实体数据

        HttpURLConnection connection = (HttpURLConnection) new URL(path)

                .openConnection();

        connection.setConnectTimeout(10000);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",

                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length",

                String.valueOf(entity.length));

        connection.setDoOutput(true);// 允许对外输出数据

        OutputStream outputStream = connection.getOutputStream();

        outputStream.write(entity);


        if (connection.getResponseCode() == 200) {

        	return changeInputStream(connection.getInputStream(),"UTF-8");

        }

        return null;

    }
	private static String changeInputStream(InputStream inputStream, String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if(inputStream !=null){
		try {
			while ((len = inputStream.read(data))!=-1) {
				outputStream.write(data,0,len);
			}
			result = new String(outputStream.toByteArray(),encode);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
		} 
		return result;
	}

    /**
134
     * 发送GET请求
135
     *
136
     * @param path

     *            请求路径

     * @param params

     *            请求参数

     * @param encoding

     *            编码

     * @return 请求是否成功

     * @throws Exception

     */

    private static String sendGETRequest(String path,

            Map<String, String> params, String encoding) throws Exception {

        StringBuilder url = new StringBuilder(path);

        url.append("?");

        for (Map.Entry<String, String> entry : params.entrySet()) {

            url.append(entry.getKey()).append("=");

            url.append(URLEncoder.encode(entry.getValue(), encoding));// 编码

            url.append('&');

        }

        url.deleteCharAt(url.length() - 1);

        HttpURLConnection connection = (HttpURLConnection) new URL(

                url.toString()).openConnection();

        connection.setConnectTimeout(10000);

        connection.setRequestMethod("GET");

        if (connection.getResponseCode() == 200) {

            return "true";

        }

        return "false";

    }

}
